<template>
    <!-- template标签下要包含一个div标签，给这个标签一个类名container -->
    <div class="container">
        <!-- 这里使用elementplus的布局容器，上面导航栏，下面显示主要内容 -->
        <el-container>
            <!-- 导航栏 -->
            <el-header>
                <div class="headerleft">
                    <div class="logo"><img src="../assets/logo.png" alt="" height="100%"></div>
                    <p class="navbtn" @click="goHome"><el-icon>
                            <House />
                        </el-icon>&nbsp;首页</p>
                    <p class="navbtn" @click="goHot"><el-icon>
                            <Loading />
                        </el-icon>&nbsp;文章</p>
                    <p class="navbtn" @click="goNotice"><el-icon>
                            <Message />
                        </el-icon>&nbsp;公告</p>
                    <p class="navbtn" @click="goTask"><el-icon>
                            <Finished />
                        </el-icon>&nbsp;任务</p>
                </div>
                <div class="headercenter">
                    __<el-icon>
                        <CollectionTag />
                    </el-icon>任务__
                </div>
                <div class="headerright">
                    <div class="person" @click="goPersonal"><el-icon>
                            <User />
                        </el-icon>个人</div>
                </div>
            </el-header>

            <!-- 主要内容 -->
            <el-main>
                <div class="left">
                    <div class="searchbar">
                        <el-input placeholder="搜索" class="searchinput" v-model="keywordstr"></el-input>
                        <el-button class="searchbtn" @click="searchArticle" type="primary">搜索</el-button>
                    </div>

                    <!-- 文章列表 -->
                    <el-scrollbar class="list">
                        <div class="listitem" v-for="(item, index) in hotsearchdata" :key="index"
                            :class="{ 'selected': nowindex === index }" @click="changeIndex(index)">

                            <p class="title_text">{{ index + 1 }}.{{ item.articleTitle }}</p>
                            <p class="title_text_num">{{ item.views }}</p>
                        </div>
                    </el-scrollbar>
                </div>

                <el-scrollbar class="right" ref="Articleref">
                    <div class="title_info">
                        <!-- 文章标题 -->
                        <div class="article_title">{{ nowindex + 1 }} . {{ article.articleTitle }}</div>
                        <div class="article_msg">
                            <div class="article_time">
                                <el-text type="primary" size="large">时间：</el-text>
                                {{ article.createTime }}
                            </div>
                            <div class="article_author">
                                <el-text type="primary" size="large">作者：</el-text>
                                {{ article.name }}
                            </div>
                            <div class="article_read">
                                <el-text type="primary" size="large">阅读量：</el-text>
                                {{ article.views }}
                            </div>
                            <div class="article_like">
                                <el-text type="primary" size="large">点赞数：</el-text>
                                {{ article.alikes }}
                                <img class="img_zan" src="../assets/zan.png" alt="" width="20px" height="20px"
                                    @click="likeArticle">
                            </div>
                        </div>
                    </div>
                    <div class="article_content">

                        <!-- 文章内容 -->
                        <div ref="Contentref" class="article_content_text"></div>


                    </div>
                    <div class="article_talk">
                        <div class="talksend">
                            <el-input v-model="talkinput" autosize type="textarea" placeholder="我有想法，发送消息" resize="none" />
                            <el-button type="primary" size="small" class="talksendbtn" @click="sendTalk">发送</el-button>

                        </div>
                        
                    </div>


                </el-scrollbar>

            </el-main>
        </el-container>
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import api from '../api/api.js';
import router from '../router';
import { userStore } from '../stores/userStore.js'
import { ElMessage } from 'element-plus'


// 定义数据(列表元素)
const hotsearchdata = ref([
    {
        aid: 0,
        articleTitle: "标题",
        views: 0
    }
])
const Contentref = ref(null)
// 定义数据(文章内容)
const article = ref({
    aid: 0,
    articleTitle: "标题",
    views: 0,
    alikes: 0,
    content: "",
    name: "作者用户名",
    createTime: "2022-01-01 12:00:00",
    like: true,
    commentList: [
        {
            uid: 0,
            avatar: "",
            name: "用户名",
            cid: 0,
            content: "评论内容",
            like: true,
            commentLikes: 0,
            commentTime: "2022-01-01 12:00:00",
        }
    ]
})

//定义数据(当前活动文章索引
const nowindex = ref(0)

// 定义数据 评论输入框内容
const talkinput = ref("")

// 定义数据 搜索框内容
const keywordstr = ref("")

//获取本地用户数据
const userInfo = userStore()
const { userid } = userInfo

const Articleref = ref(null)

// 点击文章点赞按钮
const likeArticle = async () => {
    try {
        if (userid === 0) {
            ElMessage.error("请先登录！");
            return;
        }
        if (article.value.like===false) {
            await api.addArticleLikeApi({
                aid: article.value.aid,
                uid: userid,
            })
            article.value.alikes+=1
            article.value.like=true
        } else {
            await api.cancelArticleLikeApi({aid: article.value.aid})
            article.value.alikes-=1
            article.value.like=false
        }

    } catch (err) {
        console.error("点赞文章时出错:", err);
    }
}



// 点击发送评论按钮
const sendTalk = async () => {
    try {
        let content = talkinput.value.trim();
        if (content == "") {
            return;
        }
        const res = await api.addCommentApi({
            aid: article.value.aid,
            content: content
        })
        await getArticleById(nowindex.value);

        talkinput.value = "";

    } catch (err) {
        console.error("发送评论时出错:", err);
    }
}

//界面初始化加载资源
onMounted(async () => {
    try {
        // 加载热搜列表
        await getArticleList();

        // 初始化当前显示的文章索引
        nowindex.value = 0;

        // 确保 hotsearchdata.value 已经被更新
        if (hotsearchdata.value[0].aid > 0) {
            // 加载第一个文章内容
            await getArticleById(nowindex.value);
        } else {
            console.error("热搜列表为空，无法加载文章内容");
        }

        //如果显示的文章id不等于0，则显示这个文章
        if(userInfo.nowoption!==0){
            let length=hotsearchdata.value.length
            for(let i=0;i<length;i++){
                if(hotsearchdata.value[i].aid===userInfo.nowoption){
                    changeIndex(i)
                    break
                }
            }
            userInfo.setNowOption(0)
        }

    } catch (err) {
        console.error("加载资源时出错:", err);
    }
})

// 获取文章列表
const getArticleList = async () => {
    try {
        const res = await api.getMissionListApi({});
        hotsearchdata.value = res.data.datalist;
    } catch (err) {
        console.error("获取文章列表时出错:", err);
    }
};

// 获取当前文章内容
const getArticleById = async (index) => {
    try {
        const res = await api.getArticleByIdApi({ aid: hotsearchdata.value[index].aid });
        article.value = res.data;
        Contentref.value.innerHTML = article.value.content;
    } catch (err) {
        console.error("获取文章内容时出错:", err);
    }
};

//模糊搜索文章
const searchArticle = async () => {
    try {
        const res = await api.searchArticleApi({ search: keywordstr.value, type: "article" });
        hotsearchdata.value = res.data.datalist;
    } catch (err) {
        console.error("搜索文章时出错:", err);
    }
}

//点击首页按钮
const goHome = () => {
    router.push('/')
}
// 点击热搜按钮
const goHot = () => {
    router.push('/hotsearch')
}
// 点击公告按钮
const goNotice = () => {
    router.push('/notice')
}
// 点击任务按钮
const goTask = () => {
    router.push('/task')
}
// 点击个人按钮
const goPersonal = () => {
    router.push('/login')
}

// 更换当前显示的列表索引
const changeIndex = async (index) => {
    try {
        if(index===nowindex.value){
            return
        }
        nowindex.value = index
        await getArticleById(index)
        // 页面滚动到顶部
        Articleref.value.setScrollTop(0);
    } catch (err) {
        console.error("切换文章索引时出错:", err);
    }
}
</script>

<style lang="less">
.container {
    width: 100%;
    height: 100vh;

    .el-container {
        height: 100%;

        .el-header {
            background-image: linear-gradient(to right, #fefefe, #ffffff, #409eff);
            margin: 0;
            padding: 0;
            height: 6%;
            display: flex;
            align-items: center;
            justify-content: flex-start;

            .headerleft {
                height: 100%;
                display: flex;
                align-items: center;
                width: 45%;
                font-size: 20px;

                .logo {
                    height: 100%;
                    margin-left: 10px;
                    border-radius: 50%;
                    overflow: hidden;
                }

                .navbtn {
                    margin-left: 10px;
                    user-select: none;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    padding: 0 10px;

                    &:hover {
                        background-color: #40a0ffa5;
                    }
                }
            }

            .headercenter {
                height: 100%;
                width: 10%;

                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 20px;
                color: #40a0ff;
                font-weight: bold;
            }

            .headerright {
                height: 100%;
                width: 45%;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                .person {
                    user-select: none;
                    height: 80%;
                    font-size: 20px;
                    display: flex;
                    align-items: center;
                    margin-right: 10px;
                    padding: 0 10px;
                    border-radius: 25px;

                    &:hover {
                        background-color: #abd5ff;

                    }
                }
            }
        }

        .el-main {
            background-color: #f1f1f1;
            margin: 0;
            padding: 0;
            height: 94%;
            display: flex;
            justify-content: center;
            align-items: center;

            .left {
                width: 27%;
                height: 95%;
                background: #ffffff;
                box-shadow: 5px 5px 35px #d4d4d4,
                    -5px -5px 35px #ffffff;
                border-radius: 10px;

                .searchbar {
                    padding: 10px 5px 5px;
                    height: 6%;
                    display: flex;


                }

                .list {
                    height: 94%;
                    padding: 10px;

                    .listitem {
                        // background-color: #a6e3e97e;
                        margin-top: 5px;

                        padding: 5px 5px;
                        border-radius: 5px;
                        display: flex;
                        justify-content: space-between;

                        .title_text {
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            font-size: 14px;
                        }

                        .title_text_num {
                            text-align: right;
                            font-size: 12px;
                        }
                    }

                    .listitem:hover {
                        cursor: pointer;
                        background-color: #dadada;
                    }

                    .selected {
                        background-color: #dadada;
                    }
                }


            }

            .right {
                width: 65%;
                height: 95%;
                border-radius: 10px;
                margin-left: 2%;
                overflow: auto;
                background: #ffffff;
                box-shadow: 5px 5px 35px #d4d4d4,
                    -5px -5px 35px #ffffff;
                padding: 20px;

                .title_info {
                    // background-color: #a6e3e97e;
                    border-radius: 10px;
                    padding: 10px;

                    .article_title {
                        font-size: 25px;
                    }

                    .article_msg {
                        display: flex;
                        justify-content: flex-start;
                        column-gap: 5px;
                    }
                }

                .article_content {
                    background-color: #a6e3e928;
                    border-radius: 10px;
                    padding: 10px;
                    margin-top: 10px;
                    width: 100%;

                    .article_content_text {
                        width: 100%;
                        // background-color: aqua;
                        overflow-wrap: break-word;

                        img {
                            max-width: 100%;
                        }
                    }

                }

                .article_talk {
                    // background-color: #a6e3e97e;
                    border-radius: 10px;
                    padding: 10px;
                    margin-top: 10px;

                    .talksend {
                        margin: 10px 20px;
                        // background-color: antiquewhite;
                        padding: 20px;
                        border-radius: 10px;
                        border: 2px solid #40a0ff6f;


                        .talksendbtn {
                            margin-top: 10px;
                        }
                    }

                    
                }
            }
        }
    }
}
</style>